package com.ailanyin.admin.service.impl;

import cn.hutool.core.convert.Convert;
import com.ailanyin.admin.service.SysDeptService;
import com.ailanyin.admin.service.SysUserService;
import com.ailanyin.common.annotation.DataScope;
import com.ailanyin.common.constant.UserConstants;
import com.ailanyin.common.exception.Asserts;
import com.ailanyin.common.utils.EmptyUtil;
import com.ailanyin.common.utils.SpringUtil;
import com.ailanyin.mapper.SysDeptMapper;
import com.ailanyin.mapper.SysRoleMapper;
import com.ailanyin.model.SysDept;
import com.ailanyin.model.SysRole;
import com.ailanyin.model.TreeSelect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 上午 10:24
 */
@Service
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysUserService sysUserService;

    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private SysRoleMapper roleMapper;

    /**
     * 添加部门
     *
     * @param dept dept
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDept(SysDept dept) {

        if (checkDeptNameNotUnique(dept)) {
            Asserts.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }

        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            Asserts.fail("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        dept.setCreateBy(sysUserService.getCurrentUser().getUserName());
        dept.setCreateTime(new Date());
        deptMapper.insertDept(dept);
    }

    /**
     * 修改部门
     *
     * @param dept dept
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDept(SysDept dept) {

        if (checkDeptNameNotUnique(dept)) {
            Asserts.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }

        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());

        if (EmptyUtil.isNotEmpty(newParentDept) && EmptyUtil.isNotEmpty(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }

        dept.setUpdateBy(sysUserService.getCurrentUser().getUserName());
        dept.setUpdateTime(new Date());
        deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && EmptyUtil.isNotEmpty(dept.getAncestors())
                && !"0".equals(dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
    }

    /**
     * 删除部门
     *
     * @param deptId deptId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeDept(Long deptId) {

        if (hasChildByDeptId(deptId)) {
            Asserts.fail("存在下级部门,不允许删除");
        }

        if (checkDeptExistUser(deptId)) {
            Asserts.fail("部门存在用户,不允许删除");
        }
        deptMapper.deleteDeptById(deptId);
    }

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param deptList 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> deptList) {
        List<SysDept> deptTrees = buildDeptTree(deptList);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> deptList) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : deptList) {
            tempList.add(dept.getDeptId());
        }
        for (SysDept dept : deptList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(deptList, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = deptList;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }


    /**
     * 是否存在部门子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        return deptMapper.hasChildByDeptId(deptId) > 0;
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        return deptMapper.checkDeptExistUser(deptId) > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameNotUnique(SysDept dept) {
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        return EmptyUtil.isNotEmpty(info) && !info.getDeptId().equals(dept.getDeptId());
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!sysUserService.getCurrentUser().isAdmin()) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> deptList = SpringUtil.getAopProxy(this).selectDeptList(dept);
            if (EmptyUtil.isEmpty(deptList)) {
                Asserts.fail("没有权限访问该部门数据！");
            }
        }
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 获取子节点列表
     *
     * @param list    list
     * @param sysDept sysDept
     * @return 子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept sysDept) {
        return list.stream()
                .filter(dept -> EmptyUtil.isNotEmpty(dept.getParentId()) && dept.getParentId().longValue() == sysDept.getDeptId().longValue())
                .collect(Collectors.toList());
    }

    /**
     * 判断是否有子节点
     *
     * @param list    部门列表
     * @param sysDept 部门
     * @return boolean
     */
    private boolean hasChild(List<SysDept> list, SysDept sysDept) {
        return getChildList(list, sysDept).size() > 0;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        if (children.size() > 0) {
            children.forEach(child -> child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors)));
            deptMapper.updateDeptChildren(children);
        }
    }
}
